package com.xmh.myutil.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.*;

@SuppressWarnings("unchecked")
//@Component
public class RedisClient {

    private static final String dataMapPath = new File("").getAbsolutePath() + "\\data.txt";

    private static final String dateMapPath = new File("").getAbsolutePath() + "\\date.txt";

    private static Map<String, Object> dateMap = null;

    private static Map<String, Object> dataMap = null;

    static {
        dateMap = JSONObject.parseObject(FileUtil.getFileStr(dateMapPath), Map.class);
        if (dateMap == null) {
            dateMap = new HashMap<String, Object>();
        }

        dataMap = JSONObject.parseObject(FileUtil.getFileStr(dataMapPath), Map.class);
        if (dataMap == null) {
            dataMap = new HashMap<String, Object>();
        }
    }

    public static void set(String key, Object object, long time) {
        dataMap.put(key, object);
        dateMap.put(key, new Date(new Date().getTime() + time).getTime());

        FileUtil.outFile(JSONObject.toJSONString(dateMap), dateMapPath);
        FileUtil.outFile(JSONObject.toJSONString(dataMap), dataMapPath);
    }

    public static void remove(String key) {
        dataMap.remove(key);
        dateMap.remove(key);

        FileUtil.outFile(JSONObject.toJSONString(dateMap), dateMapPath);
        FileUtil.outFile(JSONObject.toJSONString(dataMap), dataMapPath);
    }

    public static Object get(String key) {
        return dataMap.get(key);
    }

    @Scheduled(cron = "0/5 * * * * ? ")
    public static void deleteAfterCheck() {
        Set<String> keySet = dateMap.keySet();

        List<String> list = new ArrayList<>(keySet);

        Iterator<String> iterator = list.iterator();

        Date now = new Date();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            Date object = new Date((Long) dateMap.get(key));

            if (object.getTime() < now.getTime()) {
                dataMap.remove(key);
                dateMap.remove(key);
            }
        }
        FileUtil.outFile(JSONObject.toJSONString(dateMap), dateMapPath);
        FileUtil.outFile(JSONObject.toJSONString(dataMap), dataMapPath);
    }

}
